package com.gpj.learn.netty.reactor.masterslave.handler;

import com.gpj.learn.netty.reactor.masterslave.IOReactorServer;
import com.gpj.learn.netty.reactor.masterslave.pojo.ReactorInfo;

import java.io.IOException;
import java.nio.channels.*;
import java.util.List;

/**
 * @className Acceptor
 * @description TODO
 * @author GPJ
 * @date 2020/5/15 17:08
 * @version 1.0
 **/
public class Acceptor implements Runnable {
    private ServerSocketChannel serverSocketChannel;
    private Integer index = 0;
    private List<ReactorInfo> info;

    public Acceptor(ServerSocketChannel serverSocketChannel, int threadNum) {
        this.serverSocketChannel = serverSocketChannel;

        for (int i = 0; i < threadNum; i++) {
            try {
                Selector selector = Selector.open();
                IOReactorServer reactorServer = new IOReactorServer(selector);
                Thread thread = new Thread(reactorServer);
                thread.start();
                info.add(new ReactorInfo(selector, reactorServer, thread));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        try {
            if(index++ > info.size() - 1){
                index = 0;
            }

            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(true);
            SelectionKey selectionKey = socketChannel.register(info.get(index).getSelector(), SelectionKey.OP_READ);
            selectionKey.attach(new IOHandler(selectionKey, socketChannel));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
